package cn.fl.capital.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.*;
import cn.fl.capital.condition.CapPayLimCfgQueryCondition;
import cn.fl.capital.constant.CapPayLimCfgConstant;
import cn.fl.capital.service.ICapPayLimCfgService;
import cn.fl.capital.vo.CapPayLimCfgVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.ref.fncprjbscinfo.util.DateUtil;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @Description: 限额投放设置表 控制层
 */
@Controller
@RequestMapping("/capital/capPayLimCfg")
public class CapPayLimCfgController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(CapPayLimCfgController.class);

    /**
     * CapPayLimCfg 服务层BEAN
     */
    @Autowired
    private ICapPayLimCfgService capPayLimCfgService;

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载CapPayLimCfg列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capPayLimCfg/capPayLimCfgList");
        this.prepare(request, mav);
        return mav;
    }

    /**
     * 到选择资管机构列表页面
     */
    @RequestMapping(value = "/toChooseListPage.do", method = {RequestMethod.GET})
    public ModelAndView toChooseListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载到选择资管机构列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capPayLimCfg/chooseInsList");
        this.prepare(request, mav);
        return mav;
    }

    /**
     * 到新增页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toAddPage", "加载CapPayLimCfg Add页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capPayLimCfg/capPayLimCfgModify");
        this.prepare(request,mav);
        return mav;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toModifyPage", "加载CapPayLimCfg Modify页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capPayLimCfg/capPayLimCfgModify");
        this.prepare(request,mav);
        String id = request.getParameter("id");
        CapPayLimCfgVO capPayLimCfgVO = this.capPayLimCfgService.selectById(Long.valueOf(id));
        mav.addObject("capPayLimCfgVO", capPayLimCfgVO);
        return mav;
    }

    //加载数据字典数据、传值等 ？
    public void prepare(HttpServletRequest request, ModelAndView mav) {
        List<KeyValueVO> cfgTypCdList = this.capPayLimCfgService.searchCdList(CapPayLimCfgConstant.CODE_CFG_TYP_CD);
        List<KeyValueVO> limStsCdList = this.capPayLimCfgService.searchCdList(CapPayLimCfgConstant.CODE_LIM_STS_CD);
        if(CollectionUtils.isNotEmpty(cfgTypCdList)){
            mav.addObject("cfgTypCdList", JSON.toJSONString(cfgTypCdList));
        }
        if(CollectionUtils.isNotEmpty(limStsCdList)){
            mav.addObject("limStsCdList", JSON.toJSONString(limStsCdList));
        }
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initCapPayLimCfgList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        CapPayLimCfgQueryCondition qc = new CapPayLimCfgQueryCondition();
        String mgtOrgNm = request.getParameter("mgtOrgNm");
        if (StringUtils.isNotEmpty(mgtOrgNm)) {
            qc.setMgtOrgNm(mgtOrgNm);
        }
        String cfgTypCd = request.getParameter("cfgTypCd");
        if(StringUtils.isNotBlank(cfgTypCd)){
            qc.setCfgTypCd(cfgTypCd);
        }
        String limStsCd = request.getParameter("limStsCd");
        if(StringUtils.isNotBlank(limStsCd)){
            qc.setLimStsCd(limStsCd);
        }
        page.setCondition(qc);

        BaseLogUtils.info(logger, "initCapPayLimCfgList", "初始化CapPayLimCfg列表页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        Pager pager = this.capPayLimCfgService.searchListPage(page);
        List<CapPayLimCfgVO> list = (List<CapPayLimCfgVO>) pager.getResultList();
        ListPageVO<CapPayLimCfgVO> listPage = new ListPageVO<CapPayLimCfgVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO removeCapPayLimCfgByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeCapPayLimCfgByIds", "删除CapPayLimCfg数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }

        try {
            boolean success = this.capPayLimCfgService.removeByIds(idsList);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
                BaseLogUtils.info(logger, "removeCapPayLimCfgByIds", "删除CapPayLimCfg数据失败,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "removeCapPayLimCfgByIds", "删除CapPayLimCfg数据成功,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "removeCapPayLimCfgByIds", "删除CapPayLimCfg数据失败,ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "removeCapPayLimCfgByIds", "删除CapPayLimCfg数据失败,系统错误.ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getCapPayLimCfgById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "getCapPayLimCfgById", "获取CapPayLimCfg数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            CapPayLimCfgVO vo = this.capPayLimCfgService.selectById(Long.valueOf(id));
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
                BaseLogUtils.info(logger, "getCapPayLimCfgById", "获取CapPayLimCfg数据不存在,ID:" + id, CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getCapPayLimCfgById", "获取CapPayLimCfg数据成功,ID:" + id, CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "getCapPayLimCfgById", "获取CapPayLimCfg数据失败,ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "getCapPayLimCfgById", "获取CapPayLimCfg数据失败,系统错误.ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object addCapPayLimCfg(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        CapPayLimCfgVO entity = null;//获取参数
        try {
            entity = this.getRequestParamForCapPayLimCfg(request);//获取参数
            Long id = this.capPayLimCfgService.add(entity);
            result.setData(id);
            BaseLogUtils.info(logger, "addCapPayLimCfg", "新增CapPayLimCfg数据成功,ID:" + id + ".DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "addCapPayLimCfg", "新增CapPayLimCfg数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "addCapPayLimCfg", "新增CapPayLimCfg数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modifyCapPayLimCfg(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        CapPayLimCfgVO entity = null;
        try {
            entity = this.getRequestParamForCapPayLimCfg(request);
            if(StringUtils.isEmpty(entity.getMgtOrgId())){
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "资管机构不能为空.");
            }
            if (entity.getId() == null) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
                BaseLogUtils.info(logger, "modifyCapPayLimCfg", "修改CapPayLimCfg信息,主键参数为空！.", CurrentThreadContext.getCurrentUserName());
                return result;
            }

            boolean success = this.capPayLimCfgService.modify(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
                BaseLogUtils.info(logger, "modifyCapPayLimCfg", "修改CapPayLimCfg数据失败.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
                return result;
            }
            BaseLogUtils.info(logger, "modifyCapPayLimCfg", "修改CapPayLimCfg数据成功.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "modifyCapPayLimCfg", "修改CapPayLimCfg数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "modifyCapPayLimCfg", "修改CapPayLimCfg数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 获取请求参数
     *
     * @param request 请求
     * @return
     */
    private CapPayLimCfgVO getRequestParamForCapPayLimCfg(HttpServletRequest request) throws BaseException {
        //获取参数
        String id = request.getParameter("id");//主键
        String cfgTypCd = request.getParameter("cfgTypCd");//配置类型 1.自有 2.资管
        String mgtOrgId = request.getParameter("mgtOrgId");//资管机构ID
        String mgtOrgNm = request.getParameter("mgtOrgNm");//资管机构名称
        String startTm = request.getParameter("startTm");//生效时间
        //String endTm = request.getParameter("endTm");//取消时间
        String ttlAmt = request.getParameter("ttlAmt");//启用额度
        //String restAmt = request.getParameter("restAmt");//剩余额度
        String limStsCd = request.getParameter("limStsCd");//状态：1.限额  0.不限额
        String buOrgCd = request.getParameter("buOrgCd");//所属事业部

        //验证参数并赋值
        CapPayLimCfgVO entity = new CapPayLimCfgVO();
        entity.setCfgTypCd(cfgTypCd);//配置类型 1.自有 2.资管
        entity.setLimStsCd(limStsCd);//状态：1.限额  0.不限额
        entity.setBuOrgCd(buOrgCd);//所属事业部
        if(StringUtils.isNotEmpty(mgtOrgId)){
            entity.setMgtOrgId(Long.valueOf(mgtOrgId));//资管机构ID
        }
        entity.setMgtOrgNm(mgtOrgNm);//资管机构名称
        if(StringUtils.isBlank(id)){
            if(StringUtils.isNotBlank(startTm)){
                entity.setStartTm(DateUtils.formatStringToDate(startTm,DateUtils.YYYY_MM_DDHHMM));//生效时间
            }else{
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "生效时间不能为空.");
            }
            //entity.setEndTm(endTm);//取消时间
            if(StringUtils.isBlank(ttlAmt)){
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "启用额度不能为空.");
            }
            entity.setTtlAmt(DecimalUtils.convertYuanToFen(Double.parseDouble(ttlAmt)));//启用额度
            entity.setRestAmt(entity.getTtlAmt());//剩余额度
        }
        Date tm = new Date();
        if (StringUtils.isNotBlank(id)) {
            entity.setId(Long.valueOf(id));
            entity.setMdfTm(tm);
            entity.setEndTm(DateUtils.formatDate(tm,DateUtils.YYYY_MM_DDHHMM));
            entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        } else {
            entity.setCrtTm(tm);
            entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
        }

        return entity;
    }
}

